<?php
define('LESSPHP_BASE', dirname(__FILE__));
require_once LESSPHP_BASE . '/Exception.php';
require_once LESSPHP_BASE . '/Plugin/Abstract.php';
require_once LESSPHP_BASE . '/Writer/Interface.php';
class LESSPHP_PreProcessor{
	
	protected $_plugins = array();
	
	protected $_writer;
	
	public function addPlugin($plugin){
		if(is_string($plugin)){
			$class = 'LESSPHP_Plugin_' . $plugin;
			if(!class_exists($plugin) || !class_exists($class)){
				if(substr($plugin,0,8) == 'LESSPHP_'){
					$filePath = LESSPHP_BASE . '/' . str_replace('_','/', substr($plugin,8)) . '.php';
				}else{
					$filePath = LESSPHP_BASE . '/Plugin/' . $plugin . '.php';
				}
				if(!file_exists($filePath)){
					throw new LESSPHP_Exception('Class ' . $class . ' could not be found in file: ' . $filePath);
				}
				require $filePath;
				$plugin = new $class();
			}
		}
		if(!$plugin instanceof LESSPHP_Plugin_Abstract){
			throw new LESSPHP_Exception('Invalid plugin type "' . gettype($plugin) . '", "' . get_class($plugin) . '".');
		}
		$this->_plugins[] = $plugin;
	}
	
	public function addPlugins(Array $plugins){
		foreach($plugins as $plugin){
			$this->addPlugin($plugin);
		}
		return $this;
	}
	
	public function getPlugins(){
		return $this->_plugins;
	}
	
	public function getWriter(){
		if(!isset($this->_writer)) throw new LESSPHP_Exception('No LESSPHP_Writer_Interface object is set as the writer.');
		return $this->_writer;
	}
	
	public function process($css){
		$plugins = $this->getPlugins();
		foreach($plugins as $plugin){
			$css = $plugin->transformCss($css);
		}
		$css = '<css>' . $css . '</css>';
		
		$cssXml = simplexml_load_string($css);
		foreach($plugins as $plugin){
			$plugin->apply($cssXml);
		}
		
		//header('Content-type: text/xml'); echo $cssXml->asXml(); exit;
		
		$writer = $this->getWriter();
		$css = $writer->write($cssXml);
		
		return $css;
	}
	
	public function processFile($cssFile){
		$contents = file_get_contents($cssFile);
		return $this->process($contents);
	}
	
	public function setPlugins(Array $plugins){
		$this->_plugins = array();
		$this->_addPlugins($plugins);
	}
	
	public function setWriter(LESSPHP_Writer_Interface $writer){
		$this->_writer = $writer;
	}
	
}